package com.itheima.health.controller;

import com.itheima.health.common.AuthConst;
import com.itheima.health.common.MessageConst;
import com.itheima.health.pojo.result.Result;
import com.itheima.health.pojo.entity.User;
import com.itheima.health.service.UserService;
import com.itheima.health.pojo.dto.LoginDTO;
import com.itheima.health.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginDTO dto) {
        log.info("【登录】 dto:{}", dto);
        //调用service查询用户信息
        User user = userService.findByUsername(dto.getUsername());

        //用户不存在或密码不匹配则登录失败
        String password = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        if (null == user || !user.getPassword().equals(password)) {
            log.info("【登录】失败，userName:{}", dto.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL);
        }

        //模拟用户登录成功
        log.info("【登录】成功，userName:{}", user.getUsername());
        request.getSession().setAttribute("user",user);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }


    /**
     * 校验用户输入密码与数据库存储密码是否一致
     * @param inputPassword 用户输入密码
     * @param storedPassword 数据库存储密码
     * @return
     */
    private Boolean checkPassword(String inputPassword, String storedPassword) {
        if (storedPassword.startsWith(AuthConst.MD5)) {
            // 校验{md5}开头的数据库用户密码
            inputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
            storedPassword = StringUtil.getLastPart(storedPassword, AuthConst.MD5);
            return inputPassword.equals(storedPassword);
        } else if (storedPassword.startsWith(AuthConst.BCRYPT)) {
            // 校验{bcrypt}开头的数据库用户密码
            storedPassword = StringUtil.getLastPart(storedPassword, AuthConst.BCRYPT);
            return BCrypt.checkpw(inputPassword, storedPassword);
        } else {
            // 校验未加密的数据库用户密码
            return inputPassword.equals(storedPassword);
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        log.info("【退出登录】~");
        // 退出登录时移除会话中的user属性
        request.getSession().removeAttribute("user");
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    /**
     * 获取用户名
     *
     * @param request
     * @return
     */
    @GetMapping("/getUsername")
    public Result getUsername(HttpServletRequest request){
        // 从会话中获取user属性值
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }


}
